/**
 * Copyright (c) 2017, 西安星沙网络科技-版权所有
 *
 * Licensed under the GNU Lesser General Public License (LGPL) ,Version 3.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.gnu.org/licenses/lgpl-3.0.txt
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.waleychain.exchange.consumer.controller.market;

import java.math.BigDecimal;
import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import cn.waleychain.exchange.consumer.controller.BaseController;
import cn.waleychain.exchange.core.constant.DDIC;
import cn.waleychain.exchange.core.entity.PageInfo;
import cn.waleychain.exchange.core.logger.LoggerHelper;
import cn.waleychain.exchange.core.result.DefaultResult;
import cn.waleychain.exchange.core.result.IBaseResult;
import cn.waleychain.exchange.core.utils.BigDecimalUtils;
import cn.waleychain.exchange.core.utils.SequenceUtils;
import cn.waleychain.exchange.core.vaildate.VaildateHelper;
import cn.waleychain.exchange.feign.CoinServiceFeign;
import cn.waleychain.exchange.model.CoinInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@Api(description = "币相关接口")
@RestController
@RequestMapping("api/v1/coin")
public class CoinController extends BaseController {

	private static final Logger mLog = LoggerFactory.getLogger(CoinController.class);
	
	@Autowired
	private CoinServiceFeign coinFeign;
	
	@RequestMapping(value = "/fetchPageList", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	@ApiOperation(value = "分页获取币种列表", notes = "分页获取币种列表，URL: http://{ip}:{port}/{projectName}/api/v1/coin/fetchPageList", httpMethod = "GET", response = DefaultResult.class)
	public IBaseResult fetchPageList(
			@ApiParam(value = "名称", required = false) @RequestParam(required = false) String name,
			@ApiParam(value = "标题", required = false) @RequestParam(required = false) String title,
			@ApiParam(value = "币种类型", required = false) @RequestParam(required = false) Integer coinType,
			@ApiParam(value = "状态", required = false) @RequestParam(required = false) Integer status,
			@ApiParam(value = "每次查询多少条数据", required = true) @RequestParam(required = true, defaultValue = "-1") Integer showCount, 
			@ApiParam(value = "当前查询页", required = true) @RequestParam(required = true, defaultValue = "1") Integer currentPage, 
			@RequestHeader String Authorization) throws Exception {

		try {

			PageInfo<CoinInfo> page = coinFeign.fetchCoinPageList(name, title, coinType, status, showCount, currentPage);

			return DefaultResult.buildSuccessResult(page);
		} catch (Exception e) {
			LoggerHelper.printLogError(mLog, e, "分页获取币种列表");
		}

		return DefaultResult.buildSuccessResult();
	}
	
	@RequestMapping(value = "/new", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	@ApiOperation(value = "新增币种", notes = "新增币种，URL: http://{ip}:{port}/{projectName}/api/v1/coin/new", httpMethod = "POST", response = DefaultResult.class)
	public IBaseResult addCoinInfo (
			@ApiParam(value = "名称", required = true) @RequestParam String name,
			@ApiParam(value = "标题", required = true) @RequestParam String title,
			@ApiParam(value = "图标", required = true) @RequestParam Long iconResId,
			@ApiParam(value = "币种类型（1 钱包币 2 认购币）", required = true) @RequestParam Integer coinType,
			@ApiParam(value = "手续费费率", required = true) @RequestParam BigDecimal feeRate,
			@ApiParam(value = "钱包服务地址", required = true) @RequestParam String rpcIp,
			@ApiParam(value = "钱包服务端口", required = true) @RequestParam Integer rpcPort,
			@ApiParam(value = "钱包用户名", required = true) @RequestParam String rpcUser,
			@ApiParam(value = "钱包密码", required = true) @RequestParam String rpcPassword,
			@ApiParam(value = "钱包类型（0 其他 1 比特币系列 2 以太坊系列 3 以太坊代币）", required = true) @RequestParam Integer walletType,
			@ApiParam(value = "小数位数", required = true) @RequestParam(required = true) Integer scale,
			@ApiParam(value = "状态（0 无效 1 有效）", required = true) @RequestParam Integer status,
			@ApiParam(value = "是否允许提现 (0-禁止提现 1-可提现 2-提现缓慢）", required = true) @RequestParam Integer isAllowWithdraw,
			@ApiParam(value = "是否允许充值（0-禁止充值 1-可充值 2-充值缓慢）", required = true) @RequestParam Integer isAllowRecharge,
			@ApiParam(value = "是否允许交易（0 不可交易 1 可交易）", required = true) @RequestParam Integer isAllowTrade,
			@RequestHeader String Authorization) throws Exception {

		try {

			VaildateHelper.vaildateIntParams(coinType, "币种类型", DDIC.CoinType.WALLET_COIN.id, DDIC.CoinType.OFFER_BUY.id);
			VaildateHelper.vaildateIntParams(walletType, "技术类型", DDIC.WalletType.XNB.id, DDIC.WalletType.DEFAULT.id, 
					DDIC.WalletType.ETH.id, DDIC.WalletType.ETH_TOKEN.id);
			VaildateHelper.vaildateIntParams(status, "状态", DDIC.CoinStatus.DISALBED.id, DDIC.CoinStatus.ENABLED.id);
			VaildateHelper.vaildateIntParams(isAllowWithdraw, "是否允许提现", DDIC.IsAllowWithdraw.IS_ALLOW_WITHDRAW_0.id, DDIC.IsAllowWithdraw.IS_ALLOW_WITHDRAW_1.id, DDIC.IsAllowWithdraw.IS_ALLOW_WITHDRAW_2.id);
			VaildateHelper.vaildateIntParams(isAllowRecharge, "是否允许充值", DDIC.IsAllowRecharge.IS_ALLOW_RECHARGE_0.id, DDIC.IsAllowRecharge.IS_ALLOW_RECHARGE_1.id, DDIC.IsAllowRecharge.IS_ALLOW_RECHARGE_2.id);
			VaildateHelper.vaildateIntParams(isAllowTrade, "是否允许交易", DDIC.IsAllowTrade.IS_ALLOW_TRADE_0.id, DDIC.IsAllowTrade.IS_ALLOW_TRADE_1.id);
			
			CoinInfo coin = new CoinInfo();
			coin.setCoinId(SequenceUtils.generateDefaultSerialNum());
			coin.setName(name);
			coin.setTitle(title);
			coin.setIconResId(iconResId);
			coin.setCoinType(coinType);
			coin.setFeeRate(feeRate);
			coin.setMinFee(BigDecimalUtils.genInitValue());
			coin.setRpcIp(rpcIp);
			coin.setRpcPort(rpcPort);
			coin.setRpcUser(rpcUser);
			coin.setRpcPassword(rpcPassword);
			coin.setWalletType(walletType);
			coin.setScale(scale);
			coin.setStatus(status);
			coin.setSingleLimit(BigDecimalUtils.genInitValue());
			coin.setDayLimit(BigDecimalUtils.genInitValue());
			coin.setAutoWithdraw(BigDecimalUtils.genInitValue());
			coin.setIsAllowWithdraw(isAllowWithdraw);
			coin.setIsAllowRecharge(isAllowRecharge);
			coin.setCreateTime(new Date());
			coin.setModifiedTime(new Date());
			
			boolean result = coinFeign.addCoin(coin);

			return DefaultResult.buildResult(result);
		} catch (Exception e) {
			LoggerHelper.printLogError(mLog, e, "新增币种");
		}

		return DefaultResult.buildFailedResult();
	}
	
	@RequestMapping(value = "/info", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	@ApiOperation(value = "获取币种信息", notes = "获取币种信息，URL: http://{ip}:{port}/{projectName}/api/v1/coin/info", httpMethod = "GET", response = DefaultResult.class)
	public IBaseResult fetchUserInfo(
			@ApiParam(value = "标识ID", required = true) @RequestParam Long coinId, 
			@RequestHeader String Authorization) throws Exception {

		try {

			CoinInfo coin = coinFeign.fetchCoinById(coinId);

			return DefaultResult.buildSuccessResult(coin);
		} catch (Exception e) {
			LoggerHelper.printLogError(mLog, e, "获取币种信息");
		}

		return DefaultResult.buildFailedResult();
	}
	
	@RequestMapping(value = "/setCoinStatus", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	@ApiOperation(value = "设置币种状态", notes = "设置币种状态，URL: http://{ip}:{port}/{projectName}/api/v1/coin/setCoinStatus", httpMethod = "POST", response = DefaultResult.class)
	public IBaseResult setCoinStatus(
			@ApiParam(value = "标识ID", required = true) @RequestParam Long coinId, 
			@ApiParam(value = "状态（0 无效 1 有效）", required = true) @RequestParam Integer status, 
			@RequestHeader String Authorization) throws Exception {

		try {

			boolean result = coinFeign.setCoinStatus(coinId, status);

			return DefaultResult.buildResult(result);
		} catch (Exception e) {
			LoggerHelper.printLogError(mLog, e, "设置币种状态");
		}

		return DefaultResult.buildFailedResult();
	}
	
	@RequestMapping(value = "/modify", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	@ApiOperation(value = "编辑币种信息", notes = "编辑币种信息，URL: http://{ip}:{port}/{projectName}/api/v1/coin/modify", httpMethod = "POST", response = DefaultResult.class)
	public IBaseResult modify (
			@ApiParam(value = "标识ID", required = true) @RequestParam Long coinId,
			@ApiParam(value = "标题", required = true) @RequestParam String title,
			@ApiParam(value = "图标", required = true) @RequestParam Long iconResId,
			@ApiParam(value = "币种类型（1 钱包币 2 认购币）", required = true) @RequestParam Integer coinType,
			@ApiParam(value = "钱包服务地址", required = true) @RequestParam String rpcIp,
			@ApiParam(value = "钱包服务端口", required = true) @RequestParam Integer rpcPort,
			@ApiParam(value = "钱包用户名", required = true) @RequestParam String rpcUser,
			@ApiParam(value = "钱包密码", required = true) @RequestParam String rpcPassword,
			@ApiParam(value = "钱包类型（0 其他 1 比特币系列 2 以太坊系列 3 以太坊代币）", required = true) @RequestParam Integer walletType,
			@ApiParam(value = "小数位数", required = true) @RequestParam(required = true) Integer scale,
			@ApiParam(value = "状态（0 无效 1 有效）", required = true) @RequestParam Integer status,
			@ApiParam(value = "是否允许提现 (0-禁止提现 1-可提现 2-提现缓慢）", required = true) @RequestParam Integer isAllowWithdraw,
			@ApiParam(value = "是否允许充值（0-禁止充值 1-可充值 2-充值缓慢）", required = true) @RequestParam Integer isAllowRecharge,
			@ApiParam(value = "是否允许交易（0 不可交易 1 可交易）", required = true) @RequestParam Integer isAllowTrade,
			@RequestHeader String Authorization) throws Exception {

		try {

			VaildateHelper.vaildateIntParams(coinType, "币种类型", DDIC.CoinType.WALLET_COIN.id, DDIC.CoinType.OFFER_BUY.id);
			VaildateHelper.vaildateIntParams(walletType, "技术类型", DDIC.WalletType.XNB.id, DDIC.WalletType.DEFAULT.id, 
					DDIC.WalletType.ETH.id, DDIC.WalletType.ETH_TOKEN.id);
			VaildateHelper.vaildateIntParams(status, "状态", DDIC.CoinStatus.DISALBED.id, DDIC.CoinStatus.ENABLED.id);
			VaildateHelper.vaildateIntParams(isAllowWithdraw, "是否允许提现", DDIC.IsAllowWithdraw.IS_ALLOW_WITHDRAW_0.id, DDIC.IsAllowWithdraw.IS_ALLOW_WITHDRAW_1.id, DDIC.IsAllowWithdraw.IS_ALLOW_WITHDRAW_2.id);
			VaildateHelper.vaildateIntParams(isAllowRecharge, "是否允许充值", DDIC.IsAllowRecharge.IS_ALLOW_RECHARGE_0.id, DDIC.IsAllowRecharge.IS_ALLOW_RECHARGE_1.id, DDIC.IsAllowRecharge.IS_ALLOW_RECHARGE_2.id);
			VaildateHelper.vaildateIntParams(isAllowTrade, "是否允许交易", DDIC.IsAllowTrade.IS_ALLOW_TRADE_0.id, DDIC.IsAllowTrade.IS_ALLOW_TRADE_1.id);
				
			
			CoinInfo coin = new CoinInfo();
			coin.setCoinId(coinId);
			coin.setTitle(title);
			coin.setIconResId(iconResId);
			coin.setCoinType(coinType);
			coin.setRpcIp(rpcIp);
			coin.setRpcPort(rpcPort);
			coin.setRpcUser(rpcUser);
			coin.setRpcPassword(rpcPassword);
			coin.setWalletType(walletType);
			coin.setScale(scale);
			coin.setStatus(status);
			coin.setIsAllowWithdraw(isAllowWithdraw);
			coin.setIsAllowRecharge(isAllowRecharge);
			coin.setModifiedTime(new Date());
			
			boolean result = coinFeign.modifyCoinInfo(coin);

			return DefaultResult.buildResult(result);
		} catch (Exception e) {
			LoggerHelper.printLogError(mLog, e, "编辑币种信息");
		}

		return DefaultResult.buildFailedResult();
	}
	
}
